package com.zzptc.gyc;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import com.zzptc.gyc.entity.Book;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {
    // int[] pics={R.mipmap.ic_launcher,R.mipmap.ic_launcher_round};
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bitmap bitmap =(Bitmap)msg.obj;//取
            imageView.setImageBitmap(bitmap);
        }
    };
    ImageView imageView;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();//1,实例化控件
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "run: "+Thread.currentThread().getName());
                initData();//2,准备数据
            }
        }).start();
        //Log.d(TAG, "onCreate: "+Thread.currentThread().getName());
    }
    public void initData(){
        try {
            URL url=new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1604467827217&di=08d806a0b4e05671cb62690d8e82a6cf&imgtype=0&src=http%3A%2F%2Fimg.mp.itc.cn%2Fq_70%2Cc_zoom%2Cw_640%2Fupload%2F20160331%2F1bd84bca553543dfb4c400d53c5e36a3_th.jpg");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置访问方式get post
            conn.setRequestMethod("GET");
            //判断服务器的返回结果
            int code = conn.getResponseCode();
            if(code==200){
                InputStream inputStream = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                //imageView.setImageBitmap(bitmap);
                //往主线程中发消息
                Message message = handler.obtainMessage();
                message.obj=bitmap;
                handler.sendMessage(message);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void init(){
        imageView=findViewById(R.id.lv_pic);
    }
}